<?php
class Kal_Timetables_Block_Timetables extends Mage_Core_Block_Template
{
    public function getPosts()
   	{
        $collection = Mage::getModel('timetables/timetables')->getCollection()
		->addStoreFilter(Mage::app()->getStore()->getId())
		->addOrder('forder', 'asc');

		$page = $this->getRequest()->getParam('page');

		Mage::getSingleton('timetables/status')->addEnabledFilterToCollection($collection);
		
		$collection->setPageSize((int)Mage::getStoreConfig('timetables/timetables/perpage'));
        $collection->setCurPage($page);
		
		$route = Mage::getStoreConfig('timetables/timetables/route');
		if ($route == "")
		{
			$route = "timetables";
		}
		
		foreach ($collection as $item) 
		{
			$item->setAddress($this->getUrl($route) . $item->getIdentifier());
			
			$item->setCreatedTime($this->formatTime($item->getCreatedTime(),Mage::getStoreConfig('timetables/timetables/dateformat'), true));
			$item->setUpdateTime($this->formatTime($item->getUpdateTime(),Mage::getStoreConfig('timetables/timetables/dateformat'), true));
			
			if ((int)Mage::getStoreConfig('timetables/timetables/readmore') != 0)
			{
				$content = $item->getPostContent();
				$content = strip_tags($content);
				if(strlen($content) >= (int)Mage::getStoreConfig('timetables/timetables/readmore'))
				{
					$content = substr($content, 0, (int)Mage::getStoreConfig('timetables/timetables/readmore'));
					$content = substr($content, 0, strrpos($content, ' '));
					$content = $this->closetags($content);
					$content .= ' ...&nbsp;&nbsp;<a href="' . $this->getUrl($route) . $item->getIdentifier() . '" >Read More</a>';
				}
				$item->setPostContent($content);
			}
			$comments = Mage::getModel('timetables/comment')->getCollection()
			->addPostFilter($item->getPostId())
			->addApproveFilter(2);
			$item->setCommentCount(count($comments));
			
			$cats = Mage::getModel('timetables/cat')->getCollection()
			->addPostFilter($item->getPostId());
			$catUrls = array();
			foreach($cats as $cat)
			{
				$catUrls[$cat->getTitle()] = Mage::getUrl($route . "/cat/") . $cat->getIdentifier();
			}
			$item->setCats($catUrls);
		}
		return $collection;
    }
	
	public function getBookmarkHtml($post)
	{
		if (Mage::getStoreConfig('timetables/timetables/bookmarkslist'))
		{
			$this->setTemplate('timetables/bookmark.phtml');
			$this->setPost($post);
			return $this->toHtml();
		}
		return;
	}
	
	public function getCommentsEnabled()
   	{
		return Mage::getStoreConfig('timetables/comments/enabled');
	}
	
	public function getPages()
	{
		if ((int)Mage::getStoreConfig('timetables/timetables/perpage') != 0)
		{
			$collection = Mage::getModel('timetables/timetables')->getCollection()
			->addStoreFilter(Mage::app()->getStore()->getId())
			->setOrder('created_time ', 'desc');
			
			Mage::getSingleton('timetables/status')->addEnabledFilterToCollection($collection);
			
			$currentPage = (int)$this->getRequest()->getParam('page');
	
			if(!$currentPage)
			{
				$currentPage = 1;
			}
			
			$pages = ceil(count($collection) / (int)Mage::getStoreConfig('timetables/timetables/perpage'));
			
			$links = "";
			
			$route = Mage::getStoreConfig('timetables/timetables/route');
			if ($route == "")
			{
				$route = "timetables";
			}
			
			//$links = $links . '<div>';
			//Showing results 1 to 3 of 3 	Page Number:    1
			//$links = $links . '<table width="100%" border="0" cellspacing="0" cellpadding="0" class="timetables_gray_11"><tr>';
			
			$collectionfrom=($currentPage-1)*(int)Mage::getStoreConfig('timetables/timetables/perpage')+1;
			$collectionto=$collectionfrom+(int)Mage::getStoreConfig('timetables/timetables/perpage')-1;
			if($collectionto>count($collection)){
				$collectionto=count($collection);
			}
			//$links = $links . '<td align="left">Showing results ';
			//$links = $links . $collectionfrom.' to '.$collectionto.' of '.count($collection);
			//$links = $links . '</td>';
			//$links = $links . '<td align="right"> Page Number: ';
			if ($currentPage > 1)
			{
				//$links = $links . ' <a href="' . $this->getUrl($route. '/page') . (1) . '" class="timetables_page_nav">&lt; &lt; First</a> | ';
				$links = $links . ' <a href="' . $this->getUrl($route. '/page') . ($currentPage - 1) . '">&lt; Back</a> ';
			}
			//$links = $links . '<div class="right">';
			for($i=1;$i<=$pages;$i++){
				if($currentPage==$i){
					$links = $links . ' '.$i.' ';
				}else{
					$links = $links . ' <a href="' . $this->getUrl($route. '/page') . ($i) . '">'.$i.'</a> ';
				}
			}
			//$links = $links . '</div>';
			if ($currentPage < $pages)
			{
				$links = $links .  ' <a href="' . $this->getUrl($route .'/page') . ($currentPage + 1) . '" >Next &gt;</a> ';
				//$links = $links .  ' | <a href="' . $this->getUrl($route .'/page') . ($pages) . '" class="timetables_page_nav">Last &gt; &gt;</a> ';
			}
			//$links = $links . '</tr></table>';
			//$links = $links . '</div>';
			echo $links;
		}
	}
	
	public function getRecent()
   	{
		if (Mage::getStoreConfig('timetables/timetables/recent') != 0)
		{
			$collection = Mage::getModel('timetables/timetables')->getCollection()
			->addStoreFilter(Mage::app()->getStore()->getId())
			->setOrder('created_time ', 'desc');
			
			$route = Mage::getStoreConfig('timetables/timetables/route');
			if ($route == "")
			{
				$route = "timetables";
			}
			
			Mage::getSingleton('timetables/status')->addEnabledFilterToCollection($collection);
			$collection->setPageSize(Mage::getStoreConfig('timetables/timetables/recent'));
			$collection->setCurPage(1);
			foreach ($collection as $item) 
			{
				$item->setAddress($this->getUrl($route) . $item->getIdentifier());
			}
			return $collection;
		}
		else
		{
			return false;
		}
    }
	
	public function getCategories()
   	{
        $collection = Mage::getModel('timetables/cat')->getCollection()
		->addStoreFilter(Mage::app()->getStore()->getId())
		->setOrder('sort_order ', 'asc');
		
		$route = Mage::getStoreConfig('timetables/timetables/route');
		if ($route == "")
		{
			$route = "timetables";
		}
		
		foreach ($collection as $item) 
		{
			$item->setAddress($this->getUrl($route . "/cat") . $item->getIdentifier());
		}
		return $collection;
    }
	
	public function addTopLink()
    {
		$route = Mage::getStoreConfig('timetables/timetables/route');
		if ($route == "")
		{
			$route = "timetables";
		}
		$title = Mage::getStoreConfig('timetables/timetables/title');
        $this->getParentBlock()->addLink($title, $route, $title, true, array(), 15, null, 'class="top-link-timetables"');
    }
	public function addFooterLink()
    {
		$route = Mage::getStoreConfig('timetables/timetables/route');
		if ($route == "")
		{
			$route = "timetables";
		}
		$title = Mage::getStoreConfig('timetables/timetables/title');
        $this->getParentBlock()->addLink($title, $route, $title, true);
    }
	
	public function closetags($html)
	{
		#put all opened tags into an array
		preg_match_all ( "#<([a-z]+)( .*)?(?!/)>#iU", $html, $result );
		$openedtags = $result[1];
	
		#put all closed tags into an array
		preg_match_all ( "#</([a-z]+)>#iU", $html, $result );
		$closedtags = $result[1];
		$len_opened = count ( $openedtags );
		# all tags are closed
		if( count ( $closedtags ) == $len_opened )
		{
			return $html;
		}
		$openedtags = array_reverse ( $openedtags );
		# close tags
		for( $i = 0; $i < $len_opened; $i++ )
		{
			if ( !in_array ( $openedtags[$i], $closedtags ) )
			{
				$html .= "</" . $openedtags[$i] . ">";
			}
			else
			{
				unset ( $closedtags[array_search ( $openedtags[$i], $closedtags)] );
			}
		}
		return $html;
	}
}